package summary;

/**
 * @Author: 海琳琦
 * @Date: 2022/3/9 22:17
 * https://leetcode-cn.com/problems/reverse-string-ii/
 */
public class Title541 {

    public String reverseStr(String s, int k) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i += 2 * k) {
            if (s.length() - i < k) {
                sb.append(new StringBuilder(s.substring(i, s.length())).reverse());
            } else if (s.length() - i < 2 * k) {
                sb.append(new StringBuilder(s.substring(i, i + k)).reverse());
                sb.append(s, i + k, s.length());
            } else {
                sb.append(new StringBuilder(s.substring(i, i + k)).reverse());
                sb.append(s, i + k, i + 2 * k);
            }
        }
        return sb.toString();
    }



    public static String reverseStr1(String s, int k) {
        StringBuilder result = new StringBuilder();
        int n = s.length();
        for (int i = 0; i < n; i += 2 * k) {
            //当前剩余的字符
            int rest = n - i;
            if (rest < 2 * k && rest >= k) {
                result.append(new StringBuilder(s.substring(i, i + k)).reverse());
                result.append(s, i + k, n);
            } else if (rest < k) {
                result.append(new StringBuilder(s.substring(i, n)).reverse());
            } else if (rest >= 2 * k) {
                result.append(new StringBuilder(s.substring(i, i + k)).reverse());
                result.append(s, i + k, i + 2 * k);
            }
        }
        return result.toString();
    }











    public static void main(String[] args) {
        String s = "abcdefg";
        int k = 2;
        reverseStr1(s, k);
    }
}
